package com.gzhryc.shared_device.oem.micro.api.jetty;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.PatternHelper;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.LoginMemberSessionManager;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;

public class SecurityFilter implements Filter{

	static Logger log = Logger.getLogger(SecurityFilter.class);

	private static Pattern _Pat = Pattern.compile("^/paycall/.*$");
	
	private static Pattern _Pat4 = Pattern.compile("^/[0-9a-z]+/[apdmf]\\w+/images/.*$");		//本地图片
	
	PatternHelper patHelper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		patHelper = new PatternHelper();
		patHelper.addExcludePattern("/xcx/v1/wx/login/check.do");
		patHelper.addExcludePattern("/xcx/v1/wx/phone/register.do");
		patHelper.addExcludePattern("/xcx/v1/ali/login/check.do");
		patHelper.addExcludePattern("/xcx/v1/member/agreement/content.data");
		patHelper.addExcludePattern("/xcx/v1/common/resource/preload.data");		//资源预加载

		patHelper.addExcludePattern("/xcx/v1/bxscn/shop/order/qrcode.jpg");
		patHelper.addExcludePattern("/xcx/v1/member/verification_voucher/qrcode.jpg");
		patHelper.addExcludePattern("/xcx/v1/common/verifyCode.jpeg");

		patHelper.addExcludePattern("/xcx/v1/member/agent/bind.do");
		patHelper.addExcludePattern("/xcx/v1/common/sendSMS.do");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		String uri = httpRequest.getRequestURI();
		if(uri.contains("/favicon.ico")) {
			return;
		}
		
		//支付回调
		if(_Pat.matcher(uri).find()){
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		
		//匹配本地资源
		Matcher mat4 = _Pat4.matcher(uri);
		if (mat4.find()) {
			String path = PropertyTools.get().getString("localResPath") + uri;
			WebUtils.setResponseContentType(httpResponse, uri);
			WebUtils.readResource(httpResponse, path);
			return;
		}
		
		String userAgent = httpRequest.getHeader("User-Agent");
		if (MicroConstants.isDebug() == 0) {
			if (!WebUtils.isMobileOrTablet(httpRequest)) {
				log.error("访问阻止：{{0}}，userAgent = {{1}}",uri,userAgent);
				AjaxResult result = new AjaxResult(DtoConstants.NOT_POWER, "请使用手机端");
				WebUtils.toJson(httpResponse, result);
				return;
			}
		}

		if(patHelper.isExclude(uri)){
			chain.doFilter(httpRequest, httpResponse);
			return;
		}

		if (uri.endsWith(".do") || uri.endsWith(".data")) {
			String loginToken = httpRequest.getHeader("authorization");
			if (StringUtils.isNotBlank(loginToken)) {
				LoginMember loginMember = LoginMemberSessionManager.self().getMemberSession(loginToken);
				if (loginMember != null) {
					httpRequest.setAttribute(MicroConstants.ATTR_LOGIN_MEMBER, loginMember);
					chain.doFilter(httpRequest, httpResponse);
					return;
				}
			}

			DefaultAPIResponse result = new DefaultAPIResponse(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
			WebUtils.toJson(httpResponse, result);
			return;
		}else {
			AjaxResult result = new AjaxResult(DtoConstants.NOT_POWER, "您好～");
			WebUtils.toJson(httpResponse, result);
			return;
		}
	}

	@Override
	public void destroy() {}
}
